import ajax from './index'
import storage from 'utils/helper/storage'

/**
 * 接口数据缓存
 * @param {*} url 
 * @param {*} params 
 * @param {*} callback 获取数据之后回调
 * @param {*} fetch
 * @param {Boolean} immediate 获取完最新数据是否立即更新，默认不立即更新，该情况下需要callback
 */
export const setCache = (url, params, callback, fetch = 'post', immediate = false) => {
  params = params || {}
  return new Promise((resolve, reject) => {
    let name = url + JSON.stringify(params) //URl和参数决定了接口的唯一性
    let storageVal = storage.get(name)

    const requestRemote = () => {
      ajax[fetch](url, { ...params }).then(res => {
        storage.set(name, res, true)
        if (immediate && callback) {
          // 对比新旧数据
          if (JSON.stringify(res) !== JSON.stringify(storageVal)) {
            // console.log('not same')
            callback(res)
          }
        } else {
          resolve(res)
        }
      }).catch(err => {
        reject(err)
      })
    }

    requestRemote()
    // 有缓存数据，使用缓存数据
    if (storageVal) {
      if (callback) {
        callback(storageVal)
      } else {
        resolve(storageVal)
      }
    }
  })
}